package org.slusk.thynwor.util;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;

public class CgraFromCsvs {
	public static final int numGens = 1000;
	public static final int numRuns = 20;
	public static final String[] names = {
			"Fitness"
			,"FoodCollected"
			,"AttachedToFood"
			,"AssistWithFood"
			,"MoveTowardsSignal"
			,"MoveTowardGoal"
			,"HandsFull"
			,"HitObstacle"
			,"DroppedFood"
			,"ImprovementFactor"
	};
	
	
	/**
	 * @param args
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException {
		doit(args);
	}
	
	public static void doit(String[] args) throws IOException {
 		String directory = args[0];
		String runName = args[1];
		String outFileName = args[2];
		ArrayList<DStore> data = initializeData();
		int gens = data.get(0).values.length;
		int cols = data.size();
		
		Csv2StdDeviation.populateData(directory, runName, data, gens, cols);
				
		// dump to file
		dumpToFile(data, outFileName);
	}

	private static void dumpToFile(ArrayList<DStore> data, String outFileName) throws IOException {
		BufferedWriter out = new BufferedWriter(new FileWriter(outFileName));
		int gens = data.get(0).stdDevs.length;
		
		out.write("Generation,");
		
		// write column headers
		for (DStore dstore : data) {
			out.write(dstore.columnName);
			out.write(",");
		}
		
		out.write("\n");
		
		// write data
		for (int gen = 0; gen < gens; gen++) {
			out.write(gen + ",");
			for (DStore dstore : data) {
				out.write(Util.average(dstore.values[gen])+",");
				
			}
			out.write("\n");
		}
		
		out.close();
	}

	private static ArrayList<DStore> initializeData() {
		ArrayList<DStore> data = new ArrayList<DStore>(names.length);
		for (int i = 0; i < names.length; i++) {
			data.add(new DStore(names[i],numGens,numRuns));
		}
		
		return data;
	}

}
